package org.redis.cluster.redis.transport.codec.server;

import org.apache.commons.lang3.ArrayUtils;
import org.redis.cluster.redis.RedisCommand;
import org.redis.cluster.transport.ByteBuffer;
import org.redis.cluster.transport.protocol.ProtocolOutput;
import org.redis.cluster.transport.session.Session;

public class RedisServerInlineProtocolDecoder {
	
	private final static byte LINE_END='\n';
	
	private final static String PARAMETER_SPLITOR=" ";

	public void decode(RedisCommand command,ByteBuffer buffer, Session session, ProtocolOutput output) {
		if(buffer.getByte(buffer.readableBytes()-1)!=LINE_END) {
			return;
		}
		
		byte content[]=new byte[buffer.readableBytes()-2];
		buffer.readBytes(content);
		buffer.skip(2);
		
		if(ArrayUtils.isEmpty(content)) {
			return;
		}
		
		String parameterStr=new String(content);
		String parameterArray[]=parameterStr.split(PARAMETER_SPLITOR);
		
		command.setParameterCount(parameterArray.length);
		command.setParameters(new byte[command.getParameterCount()][]);
		for(int i=0;i<command.getParameterCount();i++) {
			command.getParameters()[i]=parameterArray[i].getBytes();
		}
		
		command.setSource(buffer.array());
		output.out(session, command);
	}
}